//
//  ReplyVC.swift
//  甜言蜜语
//
//  Created by yingli_yanfa_liuxingyu on 16/8/26.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import SVProgressHUD
class ReplyVC: UIViewController, UITableViewDelegate, UITableViewDataSource,NewsDetailHotReplyDelegate,RGFadeDelegate, ReplyHeaderCellDelegate, UIAlertViewDelegate, UITextFieldDelegate{
    var id: String = ""
    var modelList: allReplyInfo?{
        didSet{
            self.initRightItem()
            self.tableView.reloadData()
        }
    }
    var msg:regiestInfo?
    var type: String = ""
    var url: String = ""
    var cellHeight: CGFloat = 114
    var rgFadeView: RGFadeView?
    var requistID: String = ""
    var hasSelectedUser = false
    var replyCellHeight: CGFloat = 0.0
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var textfield: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        publicMethod.setHUDStyle()
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.textfield.delegate = self
        
        
        self.title = "回复"
        
        
        publicMethod.hiddleExtendCellForTableView(self.tableView)
        
        let cellNib = UINib(nibName: "ReplyHeaderCell", bundle: nil)
        self.tableView.registerNib(cellNib, forCellReuseIdentifier: "ReplyHeaderCell")
        
        let cellNib1 = UINib(nibName: "NewsDetailHotReplyCell1", bundle: nil)
        self.tableView.registerNib(cellNib1, forCellReuseIdentifier: "NewsDetailHotReplyCell1")
        
         NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ReplyVC.userTouched_noti(_:)), name: userHeadClicked_noti, object: nil)
        
        self.getShowInfo()
    }
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
        
        super.viewWillDisappear(animated)
    }
    override func viewWillAppear(animated: Bool) {
        self.tabBarController?.tabBar.hidden = true
    }
    deinit {
        //移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    func initRightItem(){
        let editBtn = UIButton(frame: CGRectMake(0, 0, 32, 32))
        editBtn.setTitle("删除", forState: UIControlState.Normal)
        editBtn.titleLabel?.font = UIFont.systemFontOfSize(12)
        editBtn.addTarget(self, action: #selector(self.editAction), forControlEvents:  UIControlEvents.TouchUpInside)
        let edit = UIBarButtonItem(customView: editBtn)
        self.navigationItem.rightBarButtonItem = edit

    }
    func editAction(){
        if self.modelList!.isme{
            let alertView = UIAlertView(title: "", message: "确定要删除么", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定")
            
            alertView.show()
        }else{
            let alertView = UIAlertView(title: "", message: "您不能删除评论", delegate: self, cancelButtonTitle: "确定")
            
            alertView.show()

        }
        
    }
    //MARK:alertDelegate
    func alertView(alertView: UIAlertView,clickedButtonAtIndex buttonIndex: Int){
        if (buttonIndex == 1){
            DataTool.deltecomment(id, completionHandler:{ (newModel) in
                guard newModel != nil else {
                    return
                }
                self.msg = newModel
                self.navigationController?.popToRootViewControllerAnimated(true)
            })

        }
        
    }
    //MARK:noti
    func userTouched_noti(notification:NSNotification){
        
        let id = notification.object?.valueForKey("id") as! String
        
        self.userTouched(Int(id)!)
        
    }
    //头像点击
    func userTouched(userID: Int) {
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("UserHomeTableViewController") as! UserHomeTableViewController
        vc.userId = userID
        
        self.navigationController?.pushViewController(vc, animated: true)
    }

    //MARK:tableviewDataSource
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.modelList == nil{
            return 0
        }else{
            if self.type == "行业"{
                if self.modelList!.infocomments!.count == 0{
                    return 1
                }else{
                    return 2
                }
            }else{
                if self.modelList!.actcomments!.count == 0{
                    return 1
                }else{
                    return 2
                }
            }
            
            
        }
        
       
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row == 0{
            let font = UIFont(name: "Helvetica", size: 16)
            
            if self.modelList == nil{
                return 0
            }else{
                let height = publicMethod.getLabHeigh((self.modelList?.message
                    )!, font:font!, width:SCREEN_WIDTH - 16)
                return cellHeight + height
                
            }

        }else{
            if self.type == "行业"{
                if self.modelList?.infocomments == nil{
                    return 0
                }else{
                    
                    return CGFloat((self.modelList?.infocomments!.count)! * 88 + 29)
                }
            }else{
                if self.modelList?.actcomments == nil{
                    return 0
                }else{
                    
                    for index in 0...(self.modelList?.actcomments?.count)! - 1 {
                        
                        let font = UIFont(name: "Helvetica", size: 16)
                        let height = publicMethod.getLabHeigh((self.modelList?.actcomments![index].message)!, font: font!, width: SCREEN_WIDTH - 16)
                        
                        replyCellHeight += height + 60
                      
                        
                    }
                    
                    
                    return CGFloat(replyCellHeight  + 29)
                }
            }
            
        }
       
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.row == 0{
           let cell = tableView.dequeueReusableCellWithIdentifier("ReplyHeaderCell", forIndexPath: indexPath) as! ReplyHeaderCell
            cell.delegate = self
            cell.type = self.type
            cell.modelList = self.modelList
            return cell
 
        }else{
            let cell = tableView.dequeueReusableCellWithIdentifier("NewsDetailHotReplyCell1", forIndexPath: indexPath) as! NewsDetailHotReplyCell1
            var cellInfo = self.modelList?.infocomments
            if self.type == "活动"{
                cellInfo = self.modelList?.actcomments
                cell.type = "活动"
                cell.delegate = self
            }else{
                cell.type = "回复"
                cell.delegate = self
            }
            cell.setCellContentWithCellInfo(cellInfo)
            return cell
        }
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        
    }
    
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        
        if (rgFadeView == nil) {
            rgFadeView = RGFadeView.init(frame: kScreen_frame)
            rgFadeView?.delegate = self
            self.view.addSubview(rgFadeView!)
        }
        rgFadeView?.msgTextView.becomeFirstResponder()
        
        
        return true
    }
    


    //MARK:ReplyHeaderCellDelegate
    func checkZanPersonNumber(){
        
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("ZanPersonNumberVC") as! ZanPersonNumberVC
        
        vc.modelList = self.modelList
    self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func zanSelected(){
        
    }
    
    
    //MARK:NewsDetailHotReplyDelegate
    func NewsDetailHotReply(id: String){
        self.requistID = id
        self.hasSelectedUser = true
        if (rgFadeView == nil) {
            rgFadeView = RGFadeView.init(frame: kScreen_frame)
            rgFadeView?.delegate = self
            self.view.addSubview(rgFadeView!)
        }
        rgFadeView?.msgTextView.becomeFirstResponder()
    }
    //MARK:RGFadeViewDelegate
    func sendBtnDown(text: String) {
        
        
        var jsonData = ["docid": id,"commentid": self.modelList!.id, "message": text]
        if self.type == "活动"{
            
            jsonData = ["actid": id,"commentid": self.modelList!.id, "message": text]
        }
        
        if self.hasSelectedUser == true{
            
            jsonData = ["docid": id, "message": text, "commentid":self.modelList!.id, "reply":self.requistID]
            
            if self.type == "活动"{
                
                jsonData = ["actid": id, "message": text, "commentid":self.modelList!.id, "reply":self.requistID]
            }
            
            
            
            self.hasSelectedUser = false
            
        }
        
        DataTool.sendComment(jsonData,type: self.type, completionHandler: { (isSuccess) -> Void in
            if isSuccess {
                SVProgressHUD.showSuccessWithStatus("回复成功")
                self.getShowInfo()
            } else {
                SVProgressHUD.showErrorWithStatus("回复失败")
                
            }
        })
    }

    //MARK:networking
    func getShowInfo(){
        if self.type == "行业"{
            self.url = String(format: "%@infomation/comment/comment/\(id)",BaseUrl)
           
        }else{
            self.url = String(format: "%@activity/comment/comment/\(id)",BaseUrl)
           
        }
        DataTool.userAllReply(self.url) { (modelList) -> Void in
            guard modelList != nil else{
                return
            }
            
            self.modelList = modelList
        }

    }
     
        
    
}
